package com.diao.myhub.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.diao.myhub.enums.TagTypeEnum;
import com.diao.myhub.mapper.TagMapper;
import com.diao.myhub.model.bo.TagNode;
import com.diao.myhub.model.po.Tag;
import com.diao.myhub.service.TagService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Huah
 * @description 针对表【tag(文章标签)】的数据库操作Service实现
 * @createDate 2023-10-15 15:47:15
 */
@Service
public class TagServiceImpl extends ServiceImpl<TagMapper, Tag>
        implements TagService {
    @Override
    public List<TagNode> listTagTree() {
        List<Tag> allTags = list();
        int categoryTypeCode = TagTypeEnum.CATEGORY.getTypeCode();
        int tagTypeCode = TagTypeEnum.TAG.getTypeCode();
        Map<Integer, List<Tag>> typeMap = allTags.stream().collect(Collectors.groupingBy(Tag::getType));
        Map<Long, List<Tag>> pidMap;
        if (typeMap.containsKey(tagTypeCode)) {
            List<Tag> tags = typeMap.get(tagTypeCode);
            pidMap = tags.stream().collect(Collectors.groupingBy(Tag::getPid));
        } else {
            pidMap = Collections.emptyMap();
        }
        if (typeMap.containsKey(categoryTypeCode)) {
            List<Tag> firstTags = typeMap.get(categoryTypeCode);
            return firstTags.stream().map(firstTag -> {
                TagNode tagNode = new TagNode();
                BeanUtils.copyProperties(firstTag, tagNode);
                List<TagNode> childNodes;
                List<Tag> childrenTags = pidMap.get(firstTag.getId());
                if (!CollectionUtils.isEmpty(childrenTags)) {
                    childNodes = childrenTags.stream().map(childTag -> {
                        TagNode childNode = new TagNode();
                        BeanUtils.copyProperties(childTag, childNode);
                        return childNode;
                    }).toList();
                } else {
                    childNodes = Collections.emptyList();
                }
                tagNode.setChildren(childNodes);
                return tagNode;
            }).toList();
        }
        return Collections.emptyList();
    }
}




